package setting

import (
	"github.com/go-ini/ini"
	"log"
	"time"
)

type app struct {
	JwtSecret string
	PageSize  int
	PrefixUrl string
	Name      string
}

var AppSetting = &app{}

//本服务配置
type server struct {
	RunMode      string
	HttpAddr     string
	HttpPort     int
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
	TokenExpire  int
}

var ServerSetting = &server{}

//数据库配置
type database struct {
	Type     string
	User     string
	Password string
	Host     string
	Name     string
	//TablePrefix string
}

var DatabaseSetting = &database{}

//redis配置
type redis struct {
	Host        string
	Password    string
	MaxIdle     int
	MaxActive   int
	IdleTimeout time.Duration
}

var RedisSetting = &redis{}

//微信配置
type wechat struct {
	AppID          string
	AppSecret      string
	Token          string
	EncodingAESKey string
	SmallAppID     string
}

var WechatSetting = &wechat{}

//远程服务器地址
type remoteServer struct {
	Url string
}

var RemoteServerSetting = &remoteServer{}

var cfg *ini.File

// Setup initialize the configuration instance
func Setup() {
	var err error
	cfg, err = ini.Load("conf/app.ini")
	if err != nil {
		log.Fatalf("setting.Setup, fail to parse 'conf/app.ini': %v", err)
	}

	mapTo("app", AppSetting)
	mapTo("server", ServerSetting)
	mapTo("database", DatabaseSetting)
	mapTo("redis", RedisSetting)
	mapTo("wechat", WechatSetting)
	mapTo("remote_server", RemoteServerSetting)

	//AppSetting.ImageMaxSize = AppSetting.ImageMaxSize * 1024 * 1024
	ServerSetting.ReadTimeout = ServerSetting.ReadTimeout * time.Second
	ServerSetting.WriteTimeout = ServerSetting.WriteTimeout * time.Second
	RedisSetting.IdleTimeout = RedisSetting.IdleTimeout * time.Second
}

// mapTo map section
func mapTo(section string, v interface{}) {
	err := cfg.Section(section).MapTo(v)
	if err != nil {
		log.Fatalf("Cfg.MapTo %s err: %v", section, err)
	}
}
